package com.itheima.health.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itheima.health.entity.TOrdersetting;
import com.itheima.health.pojo.vo.Region;
import com.itheima.health.service.ITOrdersettingService;
import com.itheima.health.service.impl.TOrdersettingServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class SorageListener extends AnalysisEventListener<Region> {

    private static final Logger LOGGER = LoggerFactory.getLogger(Region.class);
    //读取数据初始化值
    private static final int BATCH_COUNT = 50;
    List<TOrdersetting> list = new ArrayList<>();

    private ITOrdersettingService ordersettingService;
 
    public SorageListener(ITOrdersettingService ordersettingService) {
        this.ordersettingService = ordersettingService;
    }

    /**
     * 这个每一条数据解析都会来调用，数据是一条一条进行解析的
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Region data, AnalysisContext context) {
        TOrdersetting ordersetting = new TOrdersetting();
        ordersetting.setNumber(data.getNumber());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(data.getDate(), formatter);
        ordersetting.setOrderDate(localDate);
        list.add(ordersetting);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有excel表中数据解析完成了 都会来调用这个
     * 解释为什么要保存数据？
     *初始化读取数量为50，表中信息已经加载完毕，，假设excel表中最后只剩下30行遗留数据，所以为了防止存在遗留数据 尽量判断下集合是否为空，不为空在进行存储（这是我的逻辑需要判断，如果不需要也可进行不判断）
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
      if(list.size()==0){
         return;
      }
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    public void saveData() {
        ordersettingService.saveBatch(list); //代码实现类层保存数据
        LOGGER.info("存储数据库成功！");
    }
}
